package com.ftl.autopunch.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.ftl.autopunch.entity.SysUser;
import com.ftl.autopunch.model.LoginFormModel;
import com.ftl.autopunch.model.UserTokenModel;
import com.ftl.autopunch.service.SysUserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public R addUser(@RequestBody ArrayList<UserAndPwd> users) throws IOException {
        ArrayList<SysUser> sysUsers = new ArrayList<>();
        LoginFormModel loginFormModel = sysUserService.getLoginForm();
        try {
            for (UserAndPwd user : users) {
                SysUser sysUser = new SysUser();
                sysUser.setUsername(user.getUsername());
                sysUser.setPassword(user.getPassword());
                sysUser.setStatus(0);
                UserTokenModel userTokenModel = sysUserService.doLogin(loginFormModel, sysUser);
                if (userTokenModel.getUserSessionId() == null) {
                    throw new Exception();
                } else {
                    sysUsers.add(sysUser);
                }
            }
            sysUserService.saveBatch(sysUsers);
            return R.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            if (e.toString().contains("Duplicate")) {
                return R.failed("添加失败，用户重复！");
            } else {
                return R.failed("添加失败，用户名或密码不正确！");
            }
        }
    }

    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public R deleteUser(@RequestParam Integer id) {
        sysUserService.removeById(id);
        return R.ok("删除成功");
    }

    @GetMapping("/list")
    public R listUser() {
        try {
            List<SysUser> sysUserList = sysUserService.list();
            return R.ok(sysUserList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("获取失败");
        }
    }
}

@Data
class UserAndPwd {
    private String username;
    private String password;
}